package com.yunshipei.enterplorer.browser;


import android.content.Context;
import android.net.Uri;
import android.net.http.SslError;
import android.text.TextUtils;
import android.webkit.ValueCallback;

import com.yunshipei.common.Globals;
import com.yunshipei.core.utils.MimeTypeUtils;
import com.yunshipei.core.utils.NetUtils;
import com.yunshipei.manager.YspPreferences;

import org.xwalk.core.XWalkResourceClient;
import org.xwalk.core.XWalkView;
import org.xwalk.core.XWalkWebResourceRequest;
import org.xwalk.core.XWalkWebResourceResponse;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

public class BaseHomeWebViewClient extends XWalkResourceClient {

    Context mContext;

    public BaseHomeWebViewClient(Context context, XWalkView xWalkView) {
        super(xWalkView);
        this.mContext = context;
    }

    @Override
    public XWalkWebResourceResponse shouldInterceptLoadRequest(XWalkView view, XWalkWebResourceRequest request) {
        String url = request.getUrl().toString();

        Uri uri = Uri.parse(url);
        if (uri == null) {
            return super.shouldInterceptLoadRequest(view, request);
        }
        String encodePath = uri.getEncodedPath();
        if (TextUtils.isEmpty(encodePath)) {
            return super.shouldInterceptLoadRequest(view, request);
        }

        if (url.endsWith("_init.js")) {
            try {
                InputStream is = view.getContext().getAssets().open("empty");
                return super.createXWalkWebResourceResponse("text/javascript", "UTF-8", is);
            } catch (Exception ignored) {
            }
        }

        if (url.startsWith(Globals.APK_STATIC)) {
            String enterplorerUrl = url.replace("enterplorer://", "home/");
            try {
                InputStream localCopy = mContext.getAssets().open(enterplorerUrl);
                return super.createXWalkWebResourceResponse(MimeTypeUtils.getMimeType(view.getContext(),encodePath), "UTF-8", localCopy);
            } catch (Exception ignored) {
            }
        }

        if (url.contains("enterplorer://home/data.js")) {
            try {
                String dataJs = YspPreferences.getInstance().getSharedPreferences().getString(Globals.YSP_DATA_JS, "");
                InputStream is = new ByteArrayInputStream(dataJs.getBytes("UTF-8"));
                return super.createXWalkWebResourceResponse(MimeTypeUtils.getMimeType(view.getContext(),encodePath), "UTF-8", is);
            } catch (Exception ignored) {
            }
        }
        return super.shouldInterceptLoadRequest(view, request);
    }

    @Override
    public void onReceivedLoadError(XWalkView view, int errorCode, String description, String failingUrl) {
        switch (description) {
            case "net::ERR_ADDRESS_UNREACHABLE":
                description = "无法连接到服务器";
                break;
            case "net::ERR_CONNECTION_TIMED_OUT":
                description = "网络请求超时";
                break;
            case "net::ERR_NAME_NOT_RESOLVED":
                if (!NetUtils.isNetworkAvailable(view.getContext())) {
                    description = "网络不可用，请检查网络";
                    break;
                }
                description = "域名解析失败，请检查服务器";
                break;
            case "net::ERR_FILE_NOT_FOUND":
                description = "文件不存在";
                break;
            case "net::ERR_UNKNOWN_URL_SCHEME":
                description = "网页载入失败";
                break;
            case "net::ERR_PROXY_CONNECTION_FAILED":
                description = "代理连接失败";
                break;
            case "net::ERR_EMPTY_RESPONSE":
                description = "服务器已断开连接，且未发送任何数据";
                break;
            case "net::ERR_CACHE_READ_FAILURE":
                description = "缓存读取失败";
                break;
            default:
                break;
        }
        super.onReceivedLoadError(view, errorCode, description, failingUrl);
    }

    @Override
    public void onReceivedSslError(XWalkView view, ValueCallback<Boolean> callback, SslError error) {
        callback.onReceiveValue(true);
    }
}
